import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../util/app_util.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';

import 'package:fluwx/fluwx.dart' as fluwx;

class LoginSigninPage extends StatefulWidget {
  LoginSigninPage({Key? key}) : super(key: key);
  _LoginSigninPageState createState() => _LoginSigninPageState();
}

class _LoginSigninPageState extends State<LoginSigninPage> {
  late StreamSubscription<fluwx.BaseWeChatResponse> _wxlogin;

  GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();

  ValueChanged _onChanged = (val) => print(val);
  FirebaseAuth _auth = FirebaseAuth.instance;

  User? auser;
  String? _verificationId;

  late CancelFunc cancelLoading;

  @override
  void initState() {
    super.initState();

    _wxlogin = fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        setState(() {
          // await app_util.initLoad();
          // Navigator.pop(context);
          // _result =
          cancelLoading = BotToast.showLoading(duration: Duration(seconds: 8));
          Map<String, dynamic> lm_param = {};
          lm_param = {
            'rescode': res.code,
          };
          AppSession.appUtil.wechatLogin(lm_param).then((res) {
            if (res['ev_error'] == 0) {
              _signInWithWx(res['ev_result'], cancelLoading);
            }
          });

          print("state :${res.state} \n code:${res.code}");
        });
      }
    });
    // Provider.of<ProductDetail>(context, listen: false).fetchDetail(widget.product_id);
  }

  void _signInWithWx(String iv_token, CancelFunc iv_loading) async {
    final User? user = (await _auth.signInWithCustomToken(iv_token)).user;

    int _current_time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    // IdTokenResult _fb_result = await user.getIdToken(refresh: true);
    var fbToken = await user?.getIdToken(true);

    AppSession.prefs.setString('fb_token', fbToken ?? '');
    AppSession.prefs.setString('token_refreshed', _current_time.toString());
    AppSession.authortoken = fbToken ?? '';

    if ((AppSession.authortoken ?? '').isNotEmpty) {
      await AppSession.appUtil.initLoad();
      iv_loading();

      App.router.navigateTo(context, AppRoutes.appMain, replace: true);
      // Navigator.pop(context);
    }
  }

  void _verifyPhoneNumber() async {
    PhoneVerificationCompleted verificationCompleted =
        (PhoneAuthCredential phoneAuthCredential) async {
      await _auth.signInWithCredential(phoneAuthCredential);
    };

    PhoneVerificationFailed verificationFailed = (FirebaseAuthException authException) {
      print(authException.code);
      print(authException.message);
    };

    PhoneCodeSent codeSent = (String verificationId, [int? forceResendingToken]) async {
      _verificationId = verificationId;
      print("verificationId:"+verificationId);
    };

    PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
      _verificationId = verificationId;
      print("verificationId:"+verificationId);
    };

    try {
      await _auth.verifyPhoneNumber(
          phoneNumber: '+1' + _fbKey.currentState?.value['phone'],
          timeout: const Duration(seconds: 5),
          verificationCompleted: verificationCompleted,
          verificationFailed: verificationFailed,
          codeSent: codeSent,
          codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
      AppPopupService.showAlertSimple(
        'I',
        '已发送',
        '请耐心等待短信验证',
        iv_duration: Duration(seconds: 6),
      );
    } catch (e) {
      print(e);
      // widget._scaffold.showSnackBar(SnackBar(
      //   content: Text("Failed to Verify Phone Number: ${e}"),
      // ));
    }

    // final PhoneVerificationCompleted verificationCompleted = (AuthCredential phoneAuthCredential) {
    //   _auth.signInWithCredential(phoneAuthCredential);
    //   print(phoneAuthCredential);
    // };

    // final PhoneVerificationFailed verificationFailed = (FirebaseAuthException authException) {
    //   print(authException.code);
    //   print(authException.message);
    // };
  }

  _signInWithPhoneNumber() async {
    cancelLoading = BotToast.showLoading(duration: Duration(seconds: 8));
    try {
      final AuthCredential credential = PhoneAuthProvider.credential(
        verificationId: _verificationId??'',
        smsCode: _fbKey.currentState?.value['vcode'],
      );
      final User? user = (await _auth.signInWithCredential(credential)).user;

      // PhoneAuthCredential credential = PhoneAuthProvider.credential(
      //   verificationId: _verificationId,
      //   smsCode: _fbKey.currentState.value['vcode'],
      // );
      // PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: smsCode);

      int _current_time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      // IdTokenResult _fb_result = await user.getIdToken(refresh: true);
      var fbToken = await user?.getIdToken(true);

      AppSession.prefs.setString('fb_token', fbToken ?? '');
      AppSession.prefs.setString('token_refreshed', _current_time.toString());
      AppSession.authortoken = fbToken ?? '';
      // App.router.navigateTo(context, 'app_main', replace: true);
      cancelLoading();
      print(AppSession.authortoken);
      return fbToken ?? '';
    } catch (e) {
      print('_signInWithPhoneNumberError:'+e.toString());
    }
    // final FirebaseUser currentUser = await _auth.currentUser();
    // assert(user.uid == currentUser.uid);
    // print(currentUser);
  }

  @override
  void deactivate() {
    _wxlogin.cancel();
    super.deactivate();
  }

  // void _login(BuildContext context) async {
  //   try {
  //     print(_fbKey.currentState.value['email']);
  //     print(_fbKey.currentState.value['password']);
  //     final FirebaseUser user = (await _auth.signInWithEmailAndPassword(
  //       email: _fbKey.currentState.value['email'],
  //       password: _fbKey.currentState.value['password'],
  //     ))
  //         .user;
  //     if (user != null) {
  //       print('pass');
  //       if (user.isEmailVerified) {
  //         print('pgoodass');
  //         int _current_time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  //         IdTokenResult _fb_result = await user.getIdToken(refresh: true);
  //         LocalStorage.setString('fb_token', _fb_result.token);
  //         LocalStorage.setString('token_refreshed', _current_time.toString());
  //         AppSession.authortoken = _fb_result.token;
  //         App.router.navigateTo(context, 'app_main', replace: true);
  //       } else {
  //         await user.sendEmailVerification();
  //         print('sent');

  //         ///TODO
  //         //popup 验证
  //       }
  //     } else {
  //       print('error');

  //       ///TODO
  //       //popup error;
  //     }
  //   } on PlatformException catch (error) {
  //     // Print to console/logcat
  //     print(error);
  //     print('Error: ${error.message}');
  //   } catch (error) {
  //     // Print to console/logcat
  //     print('Error: ${error.message}');
  //   }
  // }

  // void link() async {
  //   final FirebaseAuth _auth = FirebaseAuth.instance;
  //   var _auser = await _auth.currentUser();
  //   if (_auser != null) {
  //     IdTokenResult _fb_result = await _auser.getIdToken(refresh: true);
  //     if (_fb_result.token != null) {
  //       print(_fb_result.token);
  //     } else
  //       print('22222222');
  //   } else {
  //     print('111111111');
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    // link();
    return Material(
      child: SingleChildScrollView(
        child: Container(
          // decoration: BoxDecoration(
          //   image: DecorationImage(
          //     image: AssetImage("assets/main/login_bg.png"),
          //     fit: BoxFit.cover,
          //   ),
          // ),
          height: 812.h,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                height: 560.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: 300.w,
                      child: Stack(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(
                              top: 82.h,
                            ),
                            child: Center(
                              child: Image.asset('assets/main/login_logo.png'),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Padding(
                              padding: EdgeInsets.only(
                                top: 30.h,
                              ),
                              child:
                                  Icon(Icons.clear, color: Colors.black, size: 28),
                            ),
                          ),
                        ],
                      ),
                    ),
                    FormBuilder(
                      // context,
                      key: _fbKey,
                      autovalidateMode: AutovalidateMode.always,
                      initialValue: {
                        'phone': '',
                        'vcode': '',
                      },
                      enabled: true,
                      child: Column(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 25.w),
                            padding: EdgeInsets.only(
                              left: 10.w,
                            ),
                            child: FormBuilderTextField(
                              name: "phone",
                              autofocus: true,//是否选中输入框
                              decoration: InputDecoration(
                                labelText: "手机号",
                                contentPadding: EdgeInsets.all(10.0),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                                ), //former builder⾥的弧度要⽐外边⼩
                                suffixIcon: Container(
                                  height: 26.h,
                                  width: 70.w,
                                  margin: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
                                  decoration: BoxDecoration(
                                    color: AppColor.yellowMain,
                                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                                  ),
                                  child: TextButton(
                                    onPressed: () async {
                                      FocusScope.of(context).requestFocus(FocusNode());
                                      _fbKey.currentState?.save();

                                      if ((_fbKey.currentState?.value['phone'] ?? '').isNotEmpty) {
                                        _verifyPhoneNumber();
                                      } else {}
                                    },
                                    style: ButtonStyle(
                                      overlayColor: MaterialStateColor.resolveWith((states) => Color(0x55FF8A80)),
                                    ),
                                    // highlightColor: const Color(0x55FF8A80),
                                    // splashColor: const Color(0x99FF8A80),
                                    child: Text(
                                      '发送',
                                      style: TextStyle(color: AppColor.blackMain, fontSize: 13.sp),
                                    ),
                                  ),
                                ),
                                prefixIcon: Icon(Icons.phone_in_talk, color: AppColor.yellowMain),
                              ),
                              onChanged: _onChanged,
                              // valueTransformer: (text) => num.tryParse(text),
                              validator: (value){
                                if((value??'').isEmpty){
                                  return '联系电话不能为空';
                                }else if(value!.length<9||value.length>11){
                                  return '联系电话错误';
                                }else{
                                  return null;
                                }
                              },
                              keyboardType: TextInputType.number,
                            ),
                          ),
                          SizedBox(
                            height: 30.h,
                          ),
                          Container(
                            // decoration: AppDecoration.buttonTwo, //
                            margin: EdgeInsets.symmetric(horizontal: 25.w),
                            padding: EdgeInsets.only(
                              left: 10.w,
                            ),
                            child: FormBuilderTextField(
                              name: "vcode",
                              obscureText: true,
                              maxLines: 1,
                              decoration: InputDecoration(
                                labelText: "验证码",
                                contentPadding: EdgeInsets.all(10.0),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                                ), //former builder⾥的弧度要⽐外边⼩
                                prefixIcon: Container(
                                  // width: 60,
                                  decoration: BoxDecoration(
                                      border: new Border.all(color: Colors.transparent, width: 1.0),
                                      borderRadius: BorderRadius.all(Radius.circular(9.0)),
                                      color: Colors.transparent,
                                      shape: BoxShape.rectangle),
                                  child: Icon(
                                    Icons.lock,
                                    color: AppColor.yellowMain,
                                  ),
                                ),
                              ),
                              onChanged: _onChanged,
                              // valueTransformer: (text) => num.tryParse(text),
                              validator: (value){
                                if((value??'').isEmpty){
                                  return '验证码不能为空';
                                }
                                return null;
                              },
                              keyboardType: TextInputType.number,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 16.0),
                      child: TextButton(
                        onPressed: () async {
                          var lo_cancelLoading = BotToast.showLoading(
                              duration: Duration(seconds: AppConst.maxDuration));
                          _fbKey.currentState?.save();
                          if (_fbKey.currentState!.validate()) {
                            await _signInWithPhoneNumber().then((v) async {
                              lo_cancelLoading();
                              await AppSession.appUtil.initLoad();
                              AppPopup.popupToast('S', '登录成功,重新载入');
                              // Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);

                              App.router.navigateTo(context, AppRoutes.appMain, replace: true);
                              // Navigator.pop(context);
                            });
                          }
                        },
                        child: Container(
                          width: 200.w,
                          height: 50.h,
                          decoration: AppDecoration.buttonOne,
                          child: Center(
                            child: Text(
                              '手机登录',
                              style: TextStyle(
                                // color: AppColor.goldenTwo,
                                fontWeight: FontWeight.w400,
                                fontSize: 22.sp,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    if (AppSession.wxIns)
                      Container(
                        margin: const EdgeInsets.only(top: 16.0),
                        child: TextButton(
                          onPressed: () async {
                            var lo_cancelLoading = BotToast.showLoading(
                                duration: Duration(seconds: AppConst.maxDuration));
                            fluwx
                                .sendWeChatAuth(scope: "snsapi_userinfo", state: "potato_login")
                                .then((data) {
                              print(data);
                              lo_cancelLoading();
                              // AppPopup.popupToast('S', '登录成功,重新载入中');
                            });

                            // if (_fbKey.currentState.validate()) {
                            //   await _signInWithPhoneNumber().then((v) async {

                            //   });
                            // }
                          },
                          child: Container(
                            width: 200.w,
                            height: 50.h,
                            decoration: AppDecoration.buttonLoginWechat,
                            child: Center(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset('assets/account/login_wechat.png'),
                                  Text(
                                    ' 微信登录',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.w400,
                                      fontSize: 22.sp,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
              ),

              Center(
                child: Container(
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Text(
                      '暂不登录，先逛逛 >',
                      style: TextStyle(
                        color: AppColor.blackMain,
                        fontSize: 18.sp,
                      ),
                    ),
                  ),
                  margin: EdgeInsets.only(
                    bottom: 100.h,
                    left: 60.w,
                    right: 60.w,
                  ),
                ),
              ),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}
// );
//   }
// }
